class CompanyMailer < ActionMailer::Base

  class BouncedDelivery
    attr_accessor :status_info, :original_message_id
    def self.from_email(email)
      returning(bounce = self.new) do
        status_part = email.parts.detect do |part|
          part.content_type == "message/delivery-status"
        end
        statuses = status_part.body.split(/\n/)
        bounce.status_info = statuses.inject({}) do |hash, line|
          key, value = line.split(/:/)
          hash[key] = value.strip rescue nil
          hash
        end
        original_message_part = email.parts.detect do |part|
          part.content_type == "message/rfc822"
        end
        parsed_msg = TMail::Mail.parse(original_message_part.body)
        bounce.original_message_id = parsed_msg.message_id
      end
    end
    def status
      case status_info["Status"]
      when /^5/
        "5Failure"
      when /^4/
        "4Temporary Failure"
      when /^2/
        "2Success"
      end
    end
  end

  def receive(email)
    return unless email.content_type == "multipart/report"
    bounce = BouncedDelivery.from_email(email)
    msg = SentMail.find_by_message_id(bounce.original_message_id)
    ActiveRecord::Base.transaction do
      Email.update_counters(msg.email_id, :successful_times => -2, :failure_times => 1)
      msg.update_attribute(:status, bounce.status)
    end    
  end

  def test(mail_setting)
    p mail_setting
    initialize_setting(mail_setting)
    @subject = "send for test"
    @body = {:text => "mail body(send for test)"}
    @recipients = 'mailmaster@kembo-net.com'
    @from = mail_setting.user_name
    @sent_on = Time.now
    @headers = {}
  end

  def test_mail_account(email, mail_task)
    mail_setting = email.company.mail_setting
    initialize_setting(mail_setting)
    @subject = "测试发送"
    @body[:text] =  initialize_mail_content(email , mail_task.content)
    @recipients = email.email
    @from = mail_setting.user_name
    @sent_on = Time.now
    @headers = {}
  end

  def sender(mail)
    mail_task = mail.mail_task
    setting = mail.company.mail_setting
    initialize_setting(setting)
    @subject = mail_task.subject
    #    @body[:body] =  mail.mail_task.content
    @body[:body] =  initialize_mail_content(mail.email , mail.mail_task.content)
    @recipients = mail.email.email
    @from = mail_task.sender 
    @sent_on = Time.now
    @headers = {}
  end

  #  def signup_notification(company)
  #    setup_email(company)
  #    @subject    += 'Please activate your new account'
  #    @body[:url]  = "http://YOURSITE/activate/#{company.activation_code}"
  #  end
  #
  #  def activation(company)
  #    setup_email(company)
  #    @subject    += 'Your account has been activated!'
  #    @body[:url]  = "http://YOURSITE/"
  #  end
  #
  #  protected
  #  def setup_email(company)
  #    @recipients  = "#{company.email}"
  #    @from        = "ADMINEMAIL"
  #    @subject     = "[YOURSITE] "
  #    @sent_on     = Time.now
  #    @body[:company] = company
  #  end

  private
  def initialize_setting(setting)
    if setting.blank?
      setting  = MailSetting.new({
          :address => App[:address],
          :domain =>  App[:domain],
          :user_name => App[:user_name],
          :password =>  App[:password],
          :authentication => App[:authentication]
        })
    end
    ActionMailer::Base.smtp_settings = {
      :address => setting.address,
      :domain => setting.domain,
      :user_name => setting.user_name,
      :password => setting.password,
      :authentication => setting.authentication.to_sym
    }
    ActionMailer::Base.smtp_settings[:port] =setting.port unless setting.port.blank?
    ActionMailer::Base.raise_delivery_errors = true
  end

  def initialize_mail_content(email , content)

    content.gsub(/&lt;\$ email \$&gt;/,email.email).
      gsub(/&lt;\$ second \$&gt;/,email.second).
      gsub(/&lt;\$ third \$&gt;/,email.third).
      gsub(/&lt;\$ fourth \$&gt;/,email.fourth).
      gsub(/&lt;\$ fifth \$&gt;/,email.fifth)
  end
end
